package cn.fl.continfo.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.commons.result.ResponseData;
import cn.fl.continfo.service.IPrjContCfgDtlService;
import cn.fl.continfo.transorm.ContConfigVOTransform;
import cn.fl.continfo.vo.ContConfigVO;
import cn.fl.continfo.vo.PrjContCfgDtlVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.preloan.IPrjContCfgDtlApiService;
import cn.fl.preloan.ISysContCfgApiService;
import cn.fl.preloan.condition.PrjContCfgDtlQueryCondition;
import cn.fl.preloan.condition.SysContCfgQueryCondition;
import cn.fl.preloan.constants.ContConstant;
import cn.fl.preloan.dto.PageResponseDTO;
import cn.fl.preloan.dto.PrjContCfgDtlDTO;
import cn.fl.preloan.dto.SysContCfgDTO;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Objects;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 合同配置 控制层
 */
@RestController
@RequestMapping(value = "/cont/config")
public class ContConfigController extends BaseController {

    @Autowired
    ISysContCfgApiService sysContCfgApiService;

    @Autowired
    IPrjContCfgDtlApiService prjContCfgDtlApiService;

    @Autowired
    IPrjContCfgDtlService prjContCfgDtlService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toContConfigListPage.do", method = { RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toListPage(HttpServletRequest request) {
        BaseLogUtils.newLogger("合同配置加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName()).info();
        ModelAndView view = new ModelAndView("continfo/contconfig/contConfigListPage");
        return view;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = { RequestMethod.GET, RequestMethod.POST})
    public Object initList(HttpServletRequest request) {
        BaseLogUtils.newLogger("合同配置初始化列表页面请求参数：" + this.getRequestParameter(request) + CurrentThreadContext.getCurrentUserName()).info();
        String pageNum = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String contNm = request.getParameter("contNm");//合同名称
        String contCd = request.getParameter("contCd");//合同编码
        String contTyp = request.getParameter("contTyp");//合同类型
        String signNode = request.getParameter("signNode");//签署节点
        String signWayCd = request.getParameter("signWayCd");//签署方式
        String signRole = request.getParameter("signRole");//签署角色

        SysContCfgQueryCondition sysContCfgQueryCondition = new SysContCfgQueryCondition();
        if (StringUtils.isNotEmpty(contNm)) {
            sysContCfgQueryCondition.setContNm(contNm);
        }
        if (StringUtils.isNotEmpty(contCd)) {
            sysContCfgQueryCondition.setContCd(contCd);
        }
        if (StringUtils.isNotEmpty(contTyp)) {
            sysContCfgQueryCondition.setContTyp(contTyp);
        }
        if (StringUtils.isNotEmpty(signNode)) {
            sysContCfgQueryCondition.setSignNode(signNode);
        }
        if (StringUtils.isNotEmpty(signWayCd)) {
            sysContCfgQueryCondition.setSignWayCd(signWayCd);
        }
        if (StringUtils.isNotEmpty(signRole)) {
            sysContCfgQueryCondition.setSignRole(signRole);
        }
        ListPageVO listPage = new ListPageVO();
        BaseLogUtils.newLogger("初始化列表页面查询条件sysContCfgQueryCondition" + JSON.toJSONString(sysContCfgQueryCondition)).info();
        ResponseData<PageResponseDTO> responseData = this.sysContCfgApiService.selectListPage(Integer.parseInt(pageSize), Integer.parseInt(pageNum), sysContCfgQueryCondition);
//        PageResponseDTO<SysContCfgDTO> pageDto = responseData.getData();
//        List<ContConfigVO> list = new ArrayList<>();
//        Pager pager = new Pager();
//        if(null != pageDto){
//            if(CollectionUtils.isNotEmpty(pageDto.getList())){
//                for(SysContCfgDTO dto : pageDto.getList()){
//                    ContConfigVO vo = new ContConfigVO();
//                    BeanUtils.copyProperties(dto,vo);
//                    list.add(vo);
//                }
//            }
//            pager.setTotalCount(pageDto.getTotalCount());
//        }
//        pager.setResultList(list);
        if(responseData.isSuccess()) {
        	PageResponseDTO<SysContCfgDTO> pageDto = responseData.getData();
        	listPage.setRows(pageDto.getList());
        	listPage.setTotal(pageDto.getTotalCount());
        }
        BaseLogUtils.newLogger("初始化加载列表页面返回结果pager=" + JSON.toJSONString(listPage) + CurrentThreadContext.getCurrentUserName()).info();
        return listPage;
    }

    /**
     * 到新增/修改/详情页面
     */
    @RequestMapping(value = "/toSaveOrDetailPage.do", method = { RequestMethod.GET, RequestMethod.POST })
    public ModelAndView toAddPage(HttpServletRequest request) {
        String id = request.getParameter("id");
        String detailFlag = request.getParameter("detailFlag");
        ModelAndView view = new ModelAndView("continfo/contconfig/contConfigAdd");
        view.addObject("id", id);
        view.addObject("detailFlag", detailFlag);
        if (StringUtils.isNotEmpty(id)) {
            ResponseData<SysContCfgDTO> responseData = sysContCfgApiService.selectById(Long.parseLong(id), CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
            if (responseData.isSuccess() && null != responseData.getData()) {
                ContConfigVO contConfigVO = ContConfigVOTransform.toVO(responseData.getData());
                view.addObject("contConfigVO", contConfigVO);
                if (contConfigVO != null) {
                    view.addObject("pContCd", contConfigVO.getPContCd());
                }
            }
        }
        BaseLogUtils.newLogger("合同配置加载保存页面返回结果id="+ id + ",view=" + JSON.toJSONString(view)).info();
        return view;
    }

    /**
     * 新增/修改
     */
    @RequestMapping(value = "/saveContConfig.do", method = { RequestMethod.GET, RequestMethod.POST })
    public DataResultVO saveContConfig(HttpServletRequest request) {
        BaseLogUtils.newLogger("保存合同配置数据请求参数：" + this.getRequestParameter(request) + CurrentThreadContext.getCurrentUserName()).info();
        String id = request.getParameter("id");
        String contCd = request.getParameter("contCd");
        if (StringUtils.isEmpty(id)) {
            SysContCfgQueryCondition contCfgQueryCondition = new SysContCfgQueryCondition();
            contCfgQueryCondition.setContCd(contCd);
            ResponseData<SysContCfgDTO> responseData = sysContCfgApiService.selectList(contCfgQueryCondition);
            if (responseData.isSuccess() && responseData.getData() != null) {
                return new DataResultVO(0, "合同编码已存在，请勿重复新增");
            }
        }
        ContConfigVO contConfigVO = new ContConfigVO();
        contConfigVO.setSignWayCd(request.getParameter("signWayCd"));
        contConfigVO.setContCd(contCd);
        contConfigVO.setContDesc(request.getParameter("dtlRem"));
        contConfigVO.setContDim(Integer.parseInt(request.getParameter("contDim")));
        contConfigVO.setContLvl(Integer.parseInt(request.getParameter("contLvl")));
        contConfigVO.setContNm(request.getParameter("contNm"));
        contConfigVO.setContTyp(request.getParameter("contTyp"));
        contConfigVO.setIsDel(0);
        contConfigVO.setIsLast(Integer.parseInt(request.getParameter("isLast")));
        contConfigVO.setIsVal(Integer.parseInt(request.getParameter("isVal")));
        contConfigVO.setPContCd(request.getParameter("pContCd"));
        contConfigVO.setSignInfo(request.getParameter("signInfo"));
        contConfigVO.setSignNode(request.getParameter("signNode"));
        contConfigVO.setSignRole(request.getParameter("signRole"));
        contConfigVO.setValRule(request.getParameter("valRule"));
        contConfigVO.setContDesc(request.getParameter("contDesc"));
        contConfigVO.setVersion(1L);
        contConfigVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        contConfigVO.setMdfTm(new Date());
        if (StringUtils.isNotEmpty(id)) {
            contConfigVO.setId(Long.parseLong(id));
            ResponseData<SysContCfgDTO> responseData = sysContCfgApiService.selectById(Long.parseLong(id), CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
            if (responseData.isSuccess() && responseData.getData() != null) {
                SysContCfgDTO sysContCfgDTO = responseData.getData();
                if (StringUtils.isNotEmpty(sysContCfgDTO.getContCd())) {
                    PrjContCfgDtlQueryCondition prjContCfgDtlQueryCondition = new PrjContCfgDtlQueryCondition();
                    prjContCfgDtlQueryCondition.setContCds(Arrays.asList(sysContCfgDTO.getContCd()));
                    List<PrjContCfgDtlVO> prjContCfgDtlVOS = prjContCfgDtlService.searchList(prjContCfgDtlQueryCondition);
                    for (PrjContCfgDtlVO prjContCfgDtlVO : prjContCfgDtlVOS) {
                        prjContCfgDtlVO.setContCd(contCd);
                        PrjContCfgDtlDTO dto = new PrjContCfgDtlDTO();
                        BeanUtils.copyProperties(prjContCfgDtlVO, dto);
                        ResponseData modify = prjContCfgDtlApiService.modify(dto);
                        if (!modify.isSuccess()) {
                            return new DataResultVO(0, "修改合同方案失败");
                        }
                    }
                }
            }
            ResponseData modify = sysContCfgApiService.modify(ContConfigVOTransform.toDTO(contConfigVO));
            if (modify.isSuccess()) {
                return new DataResultVO(1, "修改成功");
            }
        } else {
            contConfigVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
            contConfigVO.setOrgCd("0000");
            contConfigVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            contConfigVO.setCrtTm(new Date());
            ResponseData add = sysContCfgApiService.add(ContConfigVOTransform.toDTO(contConfigVO));
            if (add.isSuccess()) {
                return new DataResultVO(1, "新增成功");
            }
        }
        return new DataResultVO(0, "合同配置保存失败");
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
    public DataResultVO removeById(HttpServletRequest request) throws BaseException {
        BaseLogUtils.newLogger("移除对象" + this.getRequestParameter(request) + CurrentThreadContext.getCurrentUserName()).info();

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
        if(StringUtils.isEmpty(id)){
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            return result;
        }
        try {
            ResponseData<SysContCfgDTO> responseData1 = sysContCfgApiService.selectById(Long.parseLong(id), CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
            if (responseData1.isSuccess() && responseData1.getData() != null) {
                SysContCfgDTO sysContCfgDTO = responseData1.getData();
                if (StringUtils.isNotEmpty(sysContCfgDTO.getContCd())) {
                    PrjContCfgDtlQueryCondition prjContCfgDtlQueryCondition = new PrjContCfgDtlQueryCondition();
                    prjContCfgDtlQueryCondition.setContCds(Arrays.asList(sysContCfgDTO.getContCd()));
                    List<PrjContCfgDtlVO> prjContCfgDtlVOS = prjContCfgDtlService.searchList(prjContCfgDtlQueryCondition);
                    for (PrjContCfgDtlVO prjContCfgDtlVO : prjContCfgDtlVOS) {
                        ResponseData responseData = prjContCfgDtlApiService.removeById(prjContCfgDtlVO.getId());
                        if(ResponseData.FAIL_CODE.equals(responseData.getCode())){
                            result.setSuccess(BaseConstant.IS_YESNO_NO);
                            result.setInfo(prjContCfgDtlVO.getId() + "合同方案删除数据失败");
                        }
                    }
                }
            }
            ResponseData responseData = this.sysContCfgApiService.removeById(Long.valueOf(id));
            BaseLogUtils.newLogger("删除数据id=" + id + this.getRequestParameter(request) + CurrentThreadContext.getCurrentUserName()).info();
            if(ResponseData.FAIL_CODE.equals(responseData.getCode())){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(id + "删除数据失败");
            }
        }catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.newLogger("移除对象失败removeById主键id=" + id + CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
            BaseLogUtils.newLogger("移除对象失败主键id=" + id + CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.COMMON_CODE_0002);
        }
        return result;
    }

}
